const $1 = document.querySelector.bind(document);
let dom = {
    box: $1('.upload'),
    fileInput1: $1('.fileInput1'),
    fileInput2: $1('.fileInput2'),
    selectBtn1: $1('.selectBtn1'),
    selectBtn2: $1('.selectBtn2'),
    countAll: $1('.countAll'),
    successAll: $1('.successAll'),
    sizeAll: $1('.sizeAll'),
    upload: $1('.uploadBtn')
}
let info = {
    countAll: 0,
    successAll: 0,
    sizeAll: 0
}

var table = layui.table;
var element = layui.element;
var $ = layui.jquery;

// 拖拽区域
dom.box.ondragenter = (e) => {
    e.preventDefault();
}

dom.box.ondragover = (e) => {
    e.preventDefault();
}
let fileList = [];
dom.box.ondrop = async(e) => {
    e.preventDefault();
    filerFile(e.dataTransfer.items);
    reloadFileList();
}

// 把文件夹的文件过滤出来
function filerFile(files) {
    for (var item of files) {
        const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : item;
        if (entry.isDirectory) {
            const reader = entry.createReader()
            reader.readEntries(entries => {
                filerFile(entries);
            })
        }
        if (entry.isFile) {
            if(item.getAsFile){
                var file=item.getAsFile()
                if(file.type.split("/")[0]==="image"){
                    fileList.push(file);
                }
            }else{
                item.file(function(f){
                    if(f.type.split("/")[0]==="image"){
                        fileList.push(f);
                        reloadFileList();
                    }
                })
            }
        }
    }
}

// 点击大框框触发选择文件点击事件
dom.box.addEventListener('click', function () {
    dom.fileInput1.click();
})
// 监听文件选择框变化
dom.fileInput1.addEventListener('change', function (e) {
    const result =[...e.target.files];
    fileList.push(...result.filter(f=>f.type.split("/")[0]==="image"));
    reloadFileList();
})

// 监听文件夹选择框变化
dom.fileInput2.addEventListener('change', function (e) {
    const result =[...e.target.files];
    fileList.push(...result.filter(f=>f.type.split("/")[0]==="image"));
    reloadFileList();
})
// 选择文件
dom.selectBtn1.addEventListener('click', function () {
    dom.fileInput1.click();
})

// 选择文件夹
dom.selectBtn2.addEventListener('click', function () {
    dom.fileInput2.click();
})

// 渲染表格
layui.use(['table', 'element', 'jquery'], function () {
    // 渲染表格  
    function renderTable() {
        table.render({
            elem: '#ID-table-data',
            data: [],
            cols: [[
                { field: 'name', title: '文件名', minWidth: 260 },
                { field: 'type', title: '类型' },
                {
                    field: 'size', title: '大小', templet: function (row) {
                        var units = ['B', 'KB', 'MB', 'GB'];
                        var factor = Math.floor(Math.log(row.size) / Math.log(1024));
                        return (row.size / Math.pow(1024, factor)).toFixed(2) + ' ' + units[factor];
                    }
                },
                { field: 'status', title: '状态', templet: function (d) { return getStatusTemplate(d); } },
                {
                    field: 'work', title: '操作', templet: function (row) {
                        // 把索引传给操作函数
                        return `<i class="layui-icon layui-icon-delete" onclick="deleteFile('${row.LAY_INDEX}')" style="font-size: 30px;"></i>`
                    }
                }
            ]],
        });
    }

    // 获取状态栏的模板  
    function getStatusTemplate(d) {
        if (!d.status) {
            return `<span class="layui-badge-rim">待上传</span>`;
        }
        if (d.status == 1) {
            return `<span class="layui-badge layui-bg-green">已上传</span>`
        }
        return `<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="demo-filter-progress${d.LAY_INDEX}"><div class="layui-progress-bar bar${d.LAY_INDEX}" lay-percent="0%"></div></div>`;
    }

    // 渲染表格  
    renderTable();
});

// 重载表格数据
function reloadFileList() {
    table.reload('ID-table-data', {
        data: [...fileList]
    });
    updateInfo(0);
}

// 删除文件
function deleteFile(index) {
    fileList.splice(index, 1)
    reloadFileList();
}

let successCount=0;

// 更新状态
function updateInfo() {
    // 更新文件数量
    info.countAll = fileList.length;
    info.sizeAll = fileList.reduce((l, n) => n.size + l, 0);
    info.successAll = successCount;
    dom.countAll.innerHTML = "文件数量：" + info.countAll;
    dom.sizeAll.innerHTML = "总大小：" + translateSize(info.sizeAll);
    dom.successAll.innerHTML = "成功数量：" + info.successAll;
}
function translateSize(size) {
    var units = ['B', 'KB', 'MB', 'GB'];
    var factor = Math.floor(Math.log(size) / Math.log(1024));
    return (size / Math.pow(1024, factor)).toFixed(2) + ' ' + units[factor];
}

// 上传文件
dom.upload.addEventListener('click', function () {
    for (let i = 0; i < fileList.length; i++) {
        uploadFile(i);
    }
})


// 上传文件  
function uploadFile(index) {
    var fileData = fileList[index];
    var formData = new FormData();
    formData.append('file', fileData);
    $.ajax({
        url: 'http://show.shuonihao.cn/api/v1/file/qiniu',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function () {
            fileData.status = 2;
            table.reload('ID-table-data', { data: fileList }); 
        },
        xhr: function () {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    var percentComplete = ((e.loaded / e.total) * 100).toFixed(2) + '%';
                    element.progress('demo-filter-progress' + index, percentComplete);
                    updateProgress(index,percentComplete);
                }
            }, false);
            return xhr;
        },
        success: function (response) {
            fileData.status = 1;
            successCount++;
            updateInfo();
            table.reload('ID-table-data', { data: fileList });
        },
        error: function () {
            fileData.status = 2;
            table.reload('ID-table-data', { data: fileList });
        }
    });
}
// 更新进度条的值  
function updateProgress(index, percent) {
    var progressBar = $('#ID-table-data .layui-progress-bar', '#ID-table-data tbody tr:eq(' + index + ')');
    progressBar.attr('lay-percent', percent);
    element.render('progress');
}  